// @file     ServletContainerTool.groovy
// @author   Mac Radigan
// @version  $Id: ServletContainerTool.groovy 11 2010-07-14 09:31:01Z mac.radigan $

package sys.servlet

import sys.tools.Tool

import org.mortbay.jetty.*
import org.mortbay.jetty.nio.*
import org.mortbay.jetty.servlet.*
import org.mortbay.jetty.deployer.*
import groovy.servlet.*

public class ServletContainerTool extends Tool {

  public String getName() {
    return "servlet-container"
  }

  public String getDescription() {
    return "Servlet container."
  }

  public String run(String[] args) {
    def cli = new CliBuilder(usage: "${getName()} <options> [-h]")  
    cli.d(longOpt:'directory', 'directory', required:true, args:1)
    cli.p(longOpt:'port', 'port', required:false, args:1)
    cli.h(longOpt:'help', 'usage information', required:false)
    OptionAccessor opt = cli.parse(args); if(!opt) { return }
    def ant = new AntBuilder()
    runServer = { port, webappdir ->
      def server = new Server(port)
      def deployer = new WebAppDeployer()
      deployer.setContexts(server)
      deployer.setWebAppDir(webappdir)
      deployer.setExtract(true)
      deployer.setParentLoaderPriority(false)
      deployer.start()
      def rootContext = new Context(server, "/", Context.SESSIONS)
      rootContext.setResourceBase(".")
      rootContext.addServlet(new ServletHolder(new TemplateServlet()), "*.html")
      server.setStopAtShutdown(true)
      server.start()
      server.join() 
    }
    def port = 80
    if(opt.p) port = opt.p
    runServer(port, opt.d)
  }

}

// *EOF*
